package com.polytech.diploma.SQLGenerator.Oracle.DBEntityGenerators;

import java.io.Serializable;

import com.polytech.diploma.DBTablesHelper.DBEntities.MPSystemData;

public class MPAdminToolGenerator implements DBEntityGenerator, Serializable{

	private static long serialVersionUID = 1L;
	private static MPAdminToolGenerator mpAdminToolGenerator = null;
	
	public static MPAdminToolGenerator getInstance() {
		if(mpAdminToolGenerator == null)
			mpAdminToolGenerator = new MPAdminToolGenerator();
		return mpAdminToolGenerator;
	}

	public MPSystemData generateMPSystemData()
	{
		MPSystemData mpSystemData = new MPSystemData();
		String result = "DECLARE\r\n" +
				"temp1 number:=0;\r\n" +
				"temp2 number:=0;\r\n" +
				"create_stmt varchar2(1255) :=null;\r\n" +
				"BEGIN\r\n" +
				"SELECT COUNT(*) INTO temp1 FROM user_tables WHERE LOWER(TABLE_NAME) = 'mp_system_objects';\r\n" +
				"SELECT COUNT(*) INTO temp2 FROM user_tables WHERE LOWER(TABLE_NAME) = 'mp_system_object_types';\r\n" +
				"IF temp2 = 0 THEN\r\n" +
				"create_stmt := 'CREATE TABLE mp_system_object_types(" +
											"id number(10) primary key," +
											"name varchar2(255))';\r\n" +
				"EXECUTE IMMEDIATE create_stmt;\r\n";
		
		for(MPSystemObjectType type : MPSystemObjectType.values())
		{
			result += "create_stmt := 'INSERT INTO mp_system_object_types VALUES ("+ serialVersionUID +", ''"+ type.toString()+"'')';\r\n" +
					"EXECUTE IMMEDIATE create_stmt;\r\n";
			serialVersionUID++;
		}
		result += "end if;\r\n" +
				"IF temp1 = 0 THEN\r\n" +
				"create_stmt := 'CREATE TABLE mp_system_objects(" +
			"										id number(10) primary key, " +
													"name varchar2(255), " +
													"object_type number(10), " +
													"constraint fk_sys_obj_type " +
													"foreign key(object_type) " +
													"references mp_system_object_types(id))';\r\n" +
				"EXECUTE IMMEDIATE create_stmt;\r\n" +
				"end if;\r\n" +
				"END;\r\n";

		mpSystemData.setCreateScript(result);
		mpSystemData.setDropScript("DROP TABLE mp_system_objects;\r\n");
		return mpSystemData;
	}
}
